<template>
  <div v-if="visible" class="color-legend" :style="getLegendStyle()">
    <div class="legend-content">
      <div class="color-bar-container">
        <canvas ref="colorBarCanvas" :width="canvasWidth" :height="canvasHeight.value || 200"></canvas>
        <div class="legend-labels">
          <div class="label-item" v-for="(label, index) in labels" :key="index"
            :style="{ top: getLabelPosition(index) + '%' }">
            {{ label.value }}{{ unit }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '图例'
  },
  type: {
    type: String, // 'velocity' | 'scalar'
    default: 'velocity'
  },
  minValue: {
    type: Number,
    default: 0
  },
  maxValue: {
    type: Number,
    default: 10
  },
  unit: {
    type: String,
    default: 'm/s'
  },
  colorConfig: {
    type: Array,  // 标量场色彩配置
    default: () => []
  },
  position: {
    type: Object,
    default: () => ({ x: 20, y: 100 })
  }
});

const emit = defineEmits(['close']);

const colorBarCanvas = ref(null);
const canvasWidth = 20; // 减小宽度以适应更窄的侧边栏
const canvasHeight = ref(200); // 使用ref使其可动态调整
const labels = ref([]);

// 速度场默认色彩配置（黄色到红色渐变）
const velocityColorScale = [
  '#FFDC00', // 黄色
  '#FFB000',
  '#FF8000',
  '#FF6000',
  '#FF4000',
  '#FF2000',
  '#FF0000'  // 红色
];

// 生成标签
const generateLabels = () => {
  const labelCount = 6;
  labels.value = [];
  for (let i = 0; i < labelCount; i++) {
    const ratio = i / (labelCount - 1);
    const value = props.minValue + (props.maxValue - props.minValue) * (1 - ratio); // 从上到下，从大到小
    labels.value.push({
      value: value.toFixed(1),
      position: ratio * 100
    });
  }
};

// 获取标签位置
const getLabelPosition = (index) => {
  return (index / (labels.value.length - 1)) * 100;
};

// 计算canvas高度
const calculateCanvasHeight = () => {
  // 获取图例容器的高度并设置canvas高度
  if (colorBarCanvas.value) {
    const legendElement = colorBarCanvas.value.closest('.color-legend');
    if (legendElement) {
      const containerHeight = legendElement.offsetHeight;
      console.log('Container height:', containerHeight);
      // 设置为容器高度的70%，确保有足够空间显示标签，最小200px
      const newHeight = Math.max(Math.min(containerHeight * 0.7, 500), 200);
      console.log('Setting canvas height to:', newHeight);
      canvasHeight.value = newHeight;
    } else {
      // 如果找不到容器，使用默认高度
      console.log('Legend element not found, using default height');
      canvasHeight.value = 300;
    }
  } else {
    console.log('Canvas element not found');
    canvasHeight.value = 300;
  }
};

// 绘制色带
const drawColorBar = () => {
  if (!colorBarCanvas.value) {
    return;
  }

  calculateCanvasHeight();

  const canvas = colorBarCanvas.value;
  const ctx = canvas.getContext('2d');


  // 设置canvas的实际尺寸
  canvas.width = canvasWidth;
  canvas.height = canvasHeight.value;

  // 清除canvas
  ctx.clearRect(0, 0, canvasWidth, canvasHeight.value);

  if (props.type.includes('speed')) {
    // 绘制速度场色带
    const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight.value);
    velocityColorScale.forEach((color, index) => {
      const stop = index / (velocityColorScale.length - 1);
      gradient.addColorStop(stop, color);
    });
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvasWidth, canvasHeight.value);
  } else if (props.type === 'scalar' && props.colorConfig.length > 0) {
    // 绘制标量场色带
    const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight.value);
    const sortedColors = [...props.colorConfig].sort((a, b) => b.value - a.value); // 从大到小排序

    sortedColors.forEach((colorItem, index) => {
      const stop = index / (sortedColors.length - 1);
      gradient.addColorStop(stop, colorItem.color);
    });
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvasWidth, canvasHeight.value);
  } else {
    // 默认绘制速度场色带作为备用
    const gradient = ctx.createLinearGradient(0, 0, 0, canvasHeight.value);
    velocityColorScale.forEach((color, index) => {
      const stop = index / (velocityColorScale.length - 1);
      gradient.addColorStop(stop, color);
    });
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvasWidth, canvasHeight.value);
  }

};

// 获取图例样式
const getLegendStyle = () => {
  // 现在通过CSS类来控制位置，这里只返回空对象
  return {};
};

// 关闭图例
const closeLegend = () => {
  emit('close');
};

// 监听属性变化
watch([() => props.visible, () => props.minValue, () => props.maxValue, () => props.colorConfig], () => {
  if (props.visible) {
    generateLabels();
    nextTick(() => {
      // 延迟执行，确保DOM完全渲染和布局完成
      drawColorBar();
    });
  }
});

onMounted(() => {
  if (props.visible) {
    generateLabels();
    nextTick(() => {
      // 延迟执行，确保DOM完全渲染和布局完成
      drawColorBar();
    });
  }
});
</script>

<style scoped>
.color-legend {
  position: absolute;
  z-index: 1000;
  pointer-events: none;
  /* 不阻止地图交互 */
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.legend-content {
  display: flex;
  align-items: center;
  height: 80%;
  max-height: 400px;
}

.color-bar-container {
  display: flex;
  align-items: center;
  position: relative;
  height: 100%;
}

.legend-labels {
  margin-left: 4px;
  position: relative;
  height: 100%;
}

.label-item {
  position: absolute;
  font-size: 14px;
  color: #333;
  font-weight: 500;
  white-space: nowrap;
  transform: translateY(-50%);
  left: 0;
  text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.8);
}

canvas {
  border: 1px solid rgba(0, 0, 0, 0.3);
  border-radius: 2px;
}
</style>